
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError


async def http_error_handler(_: Request, exc: HTTPException):
    """
    http异常处理
    :param _:
    :param exc:
    :return:
    """
    return JSONResponse({
        "code": exc.status_code,
        "msg": exc.detail,
        "data": None
    }, status_code=exc.status_code, headers=exc.headers)


async def request_validation_error_handler(_: Request, exc: RequestValidationError):
    return JSONResponse({
        "code": 500,
        "msg": '数据数据格式不正确',
        "data": exc.__str__()
    }, status_code=500)


def register_exception(app: FastAPI)-> None:
    app.add_exception_handler(HTTPException, http_error_handler)
    app.add_exception_handler(RequestValidationError, request_validation_error_handler)
